var BOSH_SERVICE = "http://klimatur.hiof.no:8081/http-bind/ <http://klimatur.hiof.no:7070/http-bind/>";
var JID = "klimatur.hiof.no";
var connection = null;
var groupID = 'notification@conference.klimatur.hiof.no/';

var liveLocationFeedCommingEvent = new Event();
var liveMediaFeedCommingEvent = new Event();
var passTargetFeedCommingEvent = new Event();

function Event(){
    this.eventHandlers = new Array();
}

Event.prototype.addHandler = function(eventHandler){
    this.eventHandlers.push(eventHandler);
}

Event.prototype.execute = function(args){
    for(var i = 0; i < this.eventHandlers.length; i++){
        this.eventHandlers[i](args);
    }
}

function parseMessage(msg){
    if(msg != null){
        var jsonObject = jQuery.parseJSON(msg);
        if(jsonObject.type == "LiveLocationFeed"){           
            liveLocationFeedCommingEvent.execute(jsonObject);
        }        
        if(jsonObject.type == "LiveMediaFeed"){           
            liveMediaFeedCommingEvent.execute(jsonObject);
        }        
    }
}

function rawInput(data)
{
    log('RECV: ' + data);
}

function rawOutput(data)
{
    log('SENT: ' + data);
}

function onConnect(status)
{
    if (status == Strophe.Status.CONNECTING) {
    } else if (status == Strophe.Status.CONNFAIL) {
        $('#connect').get(0).value = 'connect';
    } else if (status == Strophe.Status.DISCONNECTING) {
    } else if (status == Strophe.Status.DISCONNECTED) {
        reconnect();        
    } else if (status == Strophe.Status.AUTHENTICATING) {
    } else if (status == Strophe.Status.CONNECTED) {   
        connection.addHandler(notifyUser, null, 'message', null, null,  null);
        connection.send($pres().tree());
        var pres = $pres({
            to: (groupID + connection.sid)
        });
        connection.send(pres);
    }
}

function notifyUser(message) 
{
    var elems = message.getElementsByTagName('body');
    var body = elems[0];
    var from_user = message.getAttribute('from').split('/')[0];
    parseMessage(Strophe.getText(body));
    return true;
}

function reconnect() 
{
    connection = new Strophe.Connection(BOSH_SERVICE);
    connection.connect(JID, null, onConnect);   
}

$(document).ready(function () {
    connection = new Strophe.Connection(BOSH_SERVICE);
    connection.connect(JID, null, onConnect);             
});
